package com.yileiqian.alg;

public class StringAlgorithm {
	public static int atoi(String text) {
		if (text.length() > 11) {
			throw new IllegalArgumentException();
		}
		int answer = 0;
		boolean negative = false;
		boolean maxline = false;
		for (int i = 0; i < text.length(); i++) {
			if (answer > Integer.MAX_VALUE / 10) {
				throw new IllegalArgumentException();
			}
			if(answer == Integer.MAX_VALUE/10){
				maxline = true;
			}
			
			char c = text.charAt(i);
			switch (c) {
			case '0':
				answer = answer * 10;
				break;
			case '1':
				answer = answer * 10 + 1;
				break;
			case '2':
				answer = answer * 10 + 2;
				break;
			case '3':
				answer = answer * 10 + 3;
				break;
			case '4':
				answer = answer * 10 + 4;
				break;
			case '5':
				answer = answer * 10 + 5;
				break;
			case '6':
				answer = answer * 10 + 6;
				break;
			case '7':
				answer = answer * 10 + 7;
				break;
			case '8':
				if(maxline && !negative){
					throw new IllegalArgumentException();
				}
				answer = answer * 10 + 8;
				break;
			case '9':
				if(maxline){
					throw new IllegalArgumentException();
				}
				answer = answer * 10 + 9;
				break;
			case '-':
				if (i == 0) {
					negative = true;
				} else {
					throw new IllegalArgumentException();
				}
				break;
			default:
				throw new IllegalArgumentException();
			}
		}

		if (negative) {
			answer = 0 - answer;
		}

		return answer;
	}

	public static void main(String args[]) {
		System.out.println(atoi("2147483646"));
	}
}
